package com.ruoyi.locksApi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.locksApi.service.IRemoteOpenService;
import com.ruoyi.locksApi.service.impl.ApartmentTokenTask;
import com.ruoyi.lock.config.LockApiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 远程开门服务实现类
 * 
 * @author ruoyi
 */
@Service
@Slf4j
public class RemoteOpenServiceImpl implements IRemoteOpenService {

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ApartmentTokenTask apartmentTokenTask;
    
    @Autowired
    private LockApiConfig lockApiConfig;

    @Override
    public JSONObject apartmentOpenDoorLock(Map<String, Object> params) {
        log.info("收到远程开门请求: {}", JSONObject.toJSONString(params));
        
        // 参数验证
        if (!params.containsKey("roomNum") || params.get("roomNum") == null) {
            JSONObject error = new JSONObject();
            error.put("resultCode", 500001);
            error.put("reason", "房间编号不能为空");
            return error;
        }

        // 获取token
        String tokenId = redisCache.getCacheObject("apartment:token");
        if (tokenId == null) {
            apartmentTokenTask.refreshToken();
            tokenId = redisCache.getCacheObject("apartment:token");
            if (tokenId == null) {
                JSONObject error = new JSONObject();
                error.put("resultCode", 500005);
                error.put("reason", "tokenId不存在或已过期，自动登录失败");
                return error;
            }
        }

        // 构建请求数据
        Map<String, Object> data = new HashMap<>();
        data.put("roomId", params.get("roomNum")); // 直接使用前端传来的房间编号
        
        // 如果传入了keyGroupId，则添加到请求中
        if (params.containsKey("keyGroupId") && params.get("keyGroupId") != null) {
            data.put("keyGroupId", params.get("keyGroupId"));
        }

        Map<String, Object> req = new HashMap<>();
        req.put("method", "apartmentOpenDoorLock");
        req.put("tokenId", tokenId);
        req.put("data", data);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("text/json;charset=utf-8"));
        headers.add("Content-Version", "1.1");

        HttpEntity<String> entity = new HttpEntity<>(JSONObject.toJSONString(req), headers);
        
        try {
            // 发送请求
            String respStr = restTemplate.postForObject(lockApiConfig.getLoginUrl(), entity, String.class);
            JSONObject resp = JSONObject.parseObject(respStr);
            
            // 如果token失效，自动登录并重试一次
            if (resp != null && (resp.getIntValue("resultCode") == 500005 || resp.getIntValue("resultCode") == 304)) {
                apartmentTokenTask.refreshToken();
                tokenId = redisCache.getCacheObject("apartment:token");
                req.put("tokenId", tokenId);
                entity = new HttpEntity<>(JSONObject.toJSONString(req), headers);
                respStr = restTemplate.postForObject(lockApiConfig.getLoginUrl(), entity, String.class);
                resp = JSONObject.parseObject(respStr);
            }
            
            log.info("远程开门响应: {}", JSONObject.toJSONString(resp));
            return resp;
            
        } catch (Exception e) {
            log.error("远程开门请求异常", e);
            JSONObject error = new JSONObject();
            error.put("resultCode", 500006);
            error.put("reason", "请求异常: " + e.getMessage());
            return error;
        }
    }
}
